
wait_diss_db(){
    TIMEOUT=12
    while [ $TIMEOUT -gt 0 ]; do
        state=$(docker exec diss-db pg_isready | grep "accepting connections")
        if [ $? -eq 0 ]; then
                break
        fi
        TIMEOUT=$((TIMEOUT - 1))
        sleep 5
    done
    if [ $TIMEOUT -eq 0 ]; then
    	   dc down -v
        exit 1
    fi
}



setup_db() {
    install_path="$1"
    init_data_path="$install_path/datapack/init_data"
    

    UserData=$(docker exec -t diss-db psql -h 127.0.0.1 -U diss -d diss -c "Select * from public.user" | grep "admin" | wc -l)
    if [ $UserData -eq 1 ]; then
        echo " *** system user and role data check ok *** "
        return 1
    else
       echo "init user and role data"
       echo "init data path: $init_data_path"
    fi
    
#    wait_diss_backend

    for file in `ls $init_data_path`
    do
        filepath=${install_path}/datapack/init_data/${file}
        if [[ "${filepath}" =~ .*.sql$ ]]; then
            if ! docker cp "${filepath}" diss-db:/opt; then
                echo "Unable to initialize ${file%.*}, copy initial data failed"
                return 1
            fi

            state=`docker exec -t diss-db psql -U diss -d diss -f "/opt/${file}" | grep COPY | awk -F' ' '{if($2==0) print "false"; else print "true"}'`
            if [ "${state}" != "true" ]; then
                echo "Unable to initialize ${file%.*}, process initial data failed"
                return 1
            fi
        fi
    done
}
